package com.controller.stu;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;






import java.util.UUID;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;













import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.model.DbFun;
import com.model.Dissertation;
import com.model.DraPage;
import com.model.FinalPage;
import com.model.PaperKeyTime;
import com.model.Thesissource;
import com.model.Thesistitle;


public class DissertationController extends Controller {
	//查询学生对应的老师
	public void index() 
	{
	}





//--------------------------------------------------------------------------------------------------------


///////////////////////////////////////////////2015/1/16所有页面用下面的方法


//---------------------------------------------------------------------------------------------------------
	@ActionKey("/drafpagestutable")//初稿页面表格2信息
	public void drafpagestutable(){
		String studentNo=getSessionAttr("student_no");
		String sql="select student_id from student where student_no=?";
		Record student = Db.findFirst(sql,studentNo);
		String studentid=student.getInt("student_id")+"";
		//System.out.println("stuid"+studentNo);
		  sql = "select stu_rela_thesis_id from student_rela_thesistitle where stu_rela_thesis_stu=?";
		 Record studisid = Db.findFirst(sql,studentid);
		 String stureladisid=studisid.getInt("stu_rela_thesis_id")+"";
		 sql="select * from thesismodifytemp where thesistemp_student=? and thesistemp_isstusubmit=?";
		 Record drafinfo = Db.findFirst(sql,stureladisid,"A");
			List<Object> list=new ArrayList<Object>();
			list.add(drafinfo);
			if(drafinfo==null)
			{
				 renderJson("{\"rows\":false}");
				 System.out.println("is nullllll");
			}
			else
				renderJson(list);
	
	}
	
	@ActionKey("/StuGetMemo")
	public void StuGetMemo(){

		String studentId=getPara("id");//学生ID
		String type=getPara("type");
		System.out.println("studentId: "+studentId);
		Map<String, String> map=new HashMap();
		//获取学生对应指导教师的id
		String sql="select stu_rela_guidetch_tch from student_rela_guideteacher where stu_rela_guidetch_stu=?";
		Record teacher=Db.findFirst(sql,studentId);
		System.out.println("teacherID: "+teacher.getInt("stu_rela_guidetch_tch"));
		String teacherId=teacher.getInt("stu_rela_guidetch_tch")+"";
		//根据学生教师的ID去教师指导意见表取意见
		sql="select tchmemo_memo from teachermemo where tch_meno_student=? and tchmemo_teacher=? and tchmemo_type=? ORDER BY tchmemo_time DESC LIMIT 1";
		//B代表定稿
		Record tchmemo=Db.findFirst(sql,studentId,teacherId,type);
		String tchmemoStr=tchmemo.getStr("tchmemo_memo");

            //如果论文ID存在于学生论文表，则说明论文已经被选(这是最后一道保障，确保学生选题不会重复)
            if("".equals(tchmemoStr)||tchmemoStr==null)
            {
            	map.put("text","无意见记录");
            	renderJson(map);
            	return;
            }else{
            	map.put("text",tchmemoStr);
            	renderJson(map);
            	return;
	    }
        
	}
//
//学生选题界面修改课题操作
@ActionKey("/StuEditDis")
public void StuEditDis(){
	String thesistitle= getPara("thesistitle");
	Integer thesisid= getParaToInt("thesisid");
	if("".equals(thesistitle))
		{
		renderJson("false");
		return;
		}
	//System.out.println("aaaa:--"+thesistitle+thesisid);
	Record thesis = Db.findById("thesistitle","thesistitle_id",thesisid);
	thesis.set("thesistitle_name",thesistitle);
	 if(Db.update("thesistitle","thesistitle_id",thesis))
  	   renderJson("true");
     else
  	   renderJson("false");

}


//x选题界面，给出该学生指导老师的题目
@ActionKey("/stuGetDisInfos")
public void queryDisFromTcher(){
	//sql表名与字段
	//String studentNo="04120212";//学号
	String studentNo=getSessionAttr("student_no");
	
	Integer page = getParaToInt("page");
	Integer rows = getParaToInt("rows");
	//视图名字
	String viewName="stu_selectthesis_table1_stu_thesistitle_thesissource";
	Page<Record> DisPages= Db.paginate(page,rows,"select *"," from "+viewName+" where student_no = ?",studentNo);
	Map<String, Object> m = new HashMap<String, Object>();
	m.put("total", DisPages.getTotalRow());
	m.put("rows", DisPages.getList());
	renderJson(m);
}
//获取学生所选题目
@ActionKey("/getOwnDis")
public void getstuOwnDis(){
//String stunumber = getSessionAttr("studentId");
   //String stunumber ="04120212";
	
	//String studentNo="04120212";//学号
		String studentNo=getSessionAttr("student_no");
		
   String sql="select * from stu_selectthesis_table2_student_thesistitle_thesistitlesource where student_no=?";
   Record stuThesis = Db.findFirst(sql,studentNo);
	List<Object> list=new ArrayList<Object>();
	list.add(stuThesis);
	renderJson(list);
}

//学生选题页面，选择更改论文课题20141223
	//
	//
	@ActionKey("/StuSelectDis")
	public void SelectDis(){
		//String stunumber = getSessionAttr("studentId");
		//String studentNo="04120212";
		
		//String studentNo="04120212";//学号
		String studentNo=getSessionAttr("student_no");
		
		String disId=getPara("id");//前台传的论文的ID
		System.out.println(disId);
		Record thesis;
		//查询之前是否申报过题目
		//查找学生对应的id
		String sql="select * from student where student_no=?";
	    Record student=Db.findFirst(sql,studentNo);
	    String student_id=student.getInt("student_id")+"";
	    System.out.println("学号： "+studentNo+"对应的id为 :"+student_id);
	    //在学生论文表查是否有对应论文记录,根据学生ID查
	    sql="select * from student_rela_thesistitle where stu_rela_thesis_stu=?";
	    Record stu_thesis=Db.findFirst(sql,student_id);
	    
	    //记录为空的情况
        if(stu_thesis==null){
        	System.out.println("------stu_thesis==null--------");
        	//判断论文选择状态
    	    //已经被选，返回false，结束
        	sql="select * from thesistitle where thesistitle_id=?";
        	thesis =Db.findFirst(sql,disId);
            if("A".equalsIgnoreCase(thesis.getStr("thesistitle_selected")))
            	{
            	renderJson("{\"success\":false}");
            	return;
            	}
            //如果论文未被选
            //判断学生论文表里面是否已存在该论文ID
            sql="select * from student_rela_thesistitle where stu_rela_thesis_thesis=?";
            thesis =Db.findFirst(sql,disId);
            //如果论文ID存在于学生论文表，则说明论文已经被选(这是最后一道保障，确保学生选题不会重复)
            if(thesis!=null)
            {
            	renderJson("{\"success\":false}");
            	return;
            }
          //若学生论文表不存在该论文的ID，则插入保存
            sql="select * from thesistitle where thesistitle_id=?";
        	thesis =Db.findFirst(sql,disId).set("thesistitle_selected","A");
        	Db.update("thesistitle","thesistitle_id",thesis);
        	stu_thesis=new Record().set("stu_rela_thesis_stu",student_id).set("stu_rela_thesis_thesis",disId);
	    	Db.save("student_rela_thesistitle",stu_thesis);
	    	renderJson("{\"success\":true}");
	    }
        
        
      //记录存在的情况
        if(stu_thesis!=null){
        	//判断论文选择状态
    	    //已经被选，返回false，结束
        	sql="select * from thesistitle where thesistitle_id=?";
        	thesis =Db.findFirst(sql,disId);
            if("A".equalsIgnoreCase(thesis.getStr("thesistitle_selected")))
            	{
            	System.out.println("论文已经被选1");
            	renderJson("{\"success\":false}");
            	return;
            	}
            
            //如果论文未被选
            //判断学生论文表里面是否已存在该论文ID
            sql="select * from student_rela_thesistitle where stu_rela_thesis_thesis=?";
            thesis =Db.findFirst(sql,disId);
            //如果论文ID存在于学生论文表，则说明论文已经被选(这是最后一道保障，确保学生选题不会重复)
            if(thesis!=null)
            {
            	System.out.println("论文已经被选2");
            	renderJson("{\"success\":false}");
            	return;
            }
            
        	String oldThesisId=stu_thesis.getInt("stu_rela_thesis_thesis").toString();
        	System.out.println("-------论文oldThesisId :"+oldThesisId);
        	//跟新学生论文表，将学生与论文对应
        	stu_thesis.set("stu_rela_thesis_thesis",Integer.parseInt(disId));
        	if(Db.update("student_rela_thesistitle","stu_rela_thesis_id",stu_thesis))
        	{
        	  renderJson("{\"success\":true}");
        	  //吧论文状态改为A，已经被选
        	  sql="select * from thesistitle where thesistitle_id=?";
          	  thesis =Db.findFirst(sql,disId).set("thesistitle_selected","A");
          	  Db.update("thesistitle","thesistitle_id",thesis);
          	System.out.println("论文状态已跟新A");
          	 //判断学生之前对应的论文是不是学生申报的
          	  sql="select * from teacher_rela_thesistitle where tch_rela_thesis_thesis=?";
          	  Record thesis_rel_teacher = Db.findFirst(sql,oldThesisId);
          	  //不是学生申报，则将论文状态改为B，未被选
          	  if(thesis_rel_teacher!=null)
          	  {
          		  sql="select * from thesistitle where thesistitle_id=?";
            	  thesis =Db.findFirst(sql,oldThesisId).set("thesistitle_selected","B");
            	  Db.update("thesistitle","thesistitle_id",thesis);
            	  System.out.println("oldThesisId论文状态已跟新B --"+oldThesisId);
            	  return;
          	  }
          	//是学生申报，删除原来的课题
          	 if(thesis_rel_teacher==null)
               Db.deleteById("thesistitle","thesistitle_id",oldThesisId);
               return;
        	}
        	 else
        	  renderJson("{\"success\":false}");
        	return;
        }	     
	}
	
	@ActionKey("/drafpage")//初稿页面表格信息
	public void drafpage(){
		//String stunumber = getSessionAttr("studentId");
		//String stunumber ="04120212";
		
		//String studentNo="04120212";//学号
		String studentNo=getSessionAttr("student_no");
		
		String viewname="caogao_student_thesis_source_thesismodifytemp";
	    String sql = "select * from "+viewname+" where student_no=?";
	      Record drafinfo = Db.findFirst(sql,studentNo);
			List<Object> list=new ArrayList<Object>();
			list.add(drafinfo);
			if(drafinfo==null)
			{
				 renderJson("{\"rows\":false}");
				 System.out.println("is nullllll");
			}
			else
				renderJson(list);
	
	}
	
	@ActionKey("/drafdownload")//草稿页面下载程序
	public void drafdownload(){
		
		String studentNum=getSessionAttr("stuNum")+"";//studentID
		String departmentid;//系id
		String departmentNo;//系编号
		String grade;//年级
		//查找文件存放路径
		
		//查找学生的专业id和年级
		String sql = "select student_department,student_grade from student where student_id=?";
		Record student = Db.findFirst(sql, studentNum);
		 departmentid=student.getInt("student_department")+"";//系id
		grade=student.getStr("student_grade");//年级
		sql="select department_no from department where department_id=?";
		Record studepartment = Db.findFirst(sql, departmentid);
		departmentNo=studepartment .getStr("department_no");//系编号
		//得到文件存储路径
		 String saveDir = "uploadDir"+File.separator+"teacher"+File.separator+departmentNo+File.separator+grade;
System.out.println("1111111111111111");
		String path =PathKit.getWebRootPath()+File.separator+"WEB-INF"+File.separator+saveDir+File.separator+"teacher_thesistemp_url"+File.separator;

		 sql="select thesistemp_url from caogao_student_thesis_source_thesismodifytemp where student_id=?";
			Record urlinfo = Db.findFirst(sql,studentNum);	
	        renderFile(new File(path+urlinfo.getStr("thesistemp_url")));
		 System.out.println("sssss");
		return;

	}
	//开题页面下载程序
	//
	@ActionKey("/openReportdownload")//开题页面下载程序
	public void openReportdownload(){
		String studentNum=getSessionAttr("stuNum")+"";//studentID
		String departmentid;//系id
		String departmentNo;//系编号
		String grade;//年级
		//查找文件存放路径
		
		//查找学生的专业id和年级
		String sql = "select student_department,student_grade from student where student_id=?";
		Record student = Db.findFirst(sql, studentNum);
		 departmentid=student.getInt("student_department")+"";//系id
		grade=student.getStr("student_grade");//年级
		sql="select department_no from department where department_id=?";
		Record studepartment = Db.findFirst(sql, departmentid);
		departmentNo=studepartment .getStr("department_no");//系编号
		//得到文件存储路径
		 String saveDir = "uploadDir"+File.separator+"student"+File.separator+departmentNo+File.separator+grade;
		 
		String studentid=getPara("stu_rel_thesis_id");
		//
		String path =PathKit.getWebRootPath()+File.separator+"WEB-INF"+File.separator+saveDir+File.separator+"kickoff_report"+File.separator;
        sql="select kickoff_report from kickoffreport where kickoff_student=?";
		Record urlinfo = Db.findFirst(sql,studentid);	
        renderFile(new File(path+urlinfo.getStr("kickoff_report")));
		 System.out.println("sssss");
		return;
	}


//终稿下载
	//
	@ActionKey("/finalthesisDown")
	public void  finalthesisDown(){
		String studentNum=getSessionAttr("stuNum")+"";//studentID
		String departmentid;//系id
		String departmentNo;//系编号
		String grade;//年级
		//查找文件存放路径
		
		//查找学生的专业id和年级
		String sql = "select student_department,student_grade from student where student_id=?";
		Record student = Db.findFirst(sql, studentNum);
		 departmentid=student.getInt("student_department")+"";//系id
		grade=student.getStr("student_grade");//年级
		sql="select department_no from department where department_id=?";
		Record studepartment = Db.findFirst(sql, departmentid);
		departmentNo=studepartment .getStr("department_no");//系编号
		//得到文件存储路径
		 String saveDir = "uploadDir"+File.separator+"student"+File.separator+departmentNo+File.separator+grade;

		String path =PathKit.getWebRootPath()+File.separator+"WEB-INF"+File.separator+saveDir+File.separator+"fthesis_url"+File.separator;

		 sql="select fthesis_url from zhonggao_student_teacher_thesis_finaldraft where student_id=?";
			Record urlinfo = Db.findFirst(sql,studentNum);	
	        renderFile(new File(path+urlinfo.getStr("fthesis_url")));
		 System.out.println("sssss");
		return;
	}
	
	@ActionKey("/openreportTable1")//开通报告表一
	public void opendReportTable1(){
		//String stunumber ="04120212";
		
		//String studentNo="04120212";//学号
		String studentNo=getSessionAttr("student_no");
		
		String viewname="kaitibaogao_table1_student_teacher_thesis_major_department";
	    String sql = "select * from "+viewname+" where student_no=?";
	      Record drafinfo = Db.findFirst(sql,studentNo);
			List<Object> list=new ArrayList<Object>();
			list.add(drafinfo);
			if(drafinfo==null)
			{
				 renderJson("{\"rows\":false}");
				 System.out.println("is nullllll");
			}
			else
				renderJson(list);
	}
	
	@ActionKey("/openreportTable2")//开通报告表一
	public void opendReportTable2(){
		//String stunumber ="04120212";
		
		//String studentNo="04120212";//学号
		String studentNo=getSessionAttr("student_no");
		
		String viewname="kaitibaogao_table2_student_thesis_kickoff";
	    String sql = "select * from "+viewname+" where student_no=?";
	      Record drafinfo = Db.findFirst(sql,studentNo);
			List<Object> list=new ArrayList<Object>();
			list.add(drafinfo);
			if(drafinfo==null)
			{
				 renderJson("{\"rows\":false}");
				 System.out.println("is nullllll");
			}
			else
				renderJson(list);
	}
	
	@ActionKey("/dinggaoTable")//定稿表格
	public void dinggaoTable(){
	//	String stunumber ="04120212";
		
		//String studentNo="04120212";//学号
				String studentNo=getSessionAttr("student_no");
				
		String viewname="dinggao_student_thesis_thesissource_ensuredraft";
	    String sql = "select * from "+viewname+" where student_no=?";
	      Record drafinfo = Db.findFirst(sql,studentNo);
			List<Object> list=new ArrayList<Object>();
			list.add(drafinfo);
			if(drafinfo==null)
			{
				 renderJson("{\"rows\":false}");
				 System.out.println("is nullllll");
			}
			else
				renderJson(list);
	}
	
	@ActionKey("/finalthesisTable")//终稿表格数据
	public void finalthesisTable(){
	//	String stunumber ="04120212";
		
		//String studentNo="04120212";//学号
		String studentNo=getSessionAttr("student_no");
		
		String viewname="zhonggao_student_teacher_thesis_finaldraft";
	    String sql = "select * from "+viewname+" where student_no=?";
	      Record drafinfo = Db.findFirst(sql,studentNo);
			List<Object> list=new ArrayList<Object>();
			list.add(drafinfo);
			if(drafinfo==null)
			{
				 renderJson("{\"rows\":false}");
				 System.out.println("is nullllll");
			}
			else
				renderJson(list);
	}
	public void moveFile(String saveDir,String sourceFileName){
		String savepath =PathKit.getWebRootPath()+"/WEB-INF/"+saveDir;//文件保存路径
		FileInputStream in;
		try {
			in = new FileInputStream(savepath + File.separator + sourceFileName);

			savepath=savepath+"_first";
			File file = new File(savepath);
			if(!file.exists()){
				file.mkdirs();
			}
			
		FileOutputStream out = new FileOutputStream(savepath + File.separator +"first_"+sourceFileName);
		int len = 0;
		byte buffer[] = new byte[1024];
		while((len=in.read(buffer))>0){
			out.write(buffer, 0, len);
		}
		in.close();
		out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@ActionKey("/mystuupload")
	public void uploadTest() throws  IOException {
		String fileType=null;
		
		
		//String stunumber ="04120212";
		
		//String studentNo="04120212";//学号
		String studentNum=getSessionAttr("stuNum")+"";//studentID
		String departmentid;//系id
		String departmentNo;//系编号
		String grade;//年级
		
				String studentNo=getSessionAttr("student_no");
				
		String studentName=getSessionAttr("student_name");;
		String sql="";
		String saveDir = null;
		String saveFileName = null;
		boolean bool=false;//判断上传成功或者失败
		try{
			DiskFileItemFactory factory = new DiskFileItemFactory();  //默认10k
			factory.setSizeThreshold(1024*1024);//缓存大小
			System.out.println(PathKit.getWebRootPath()+"--------");
			//String cacheDirPath=this.getRequest().getServletContext().getRealPath("/WEB-INF/uploadcache");//缓存目录 tomcat7可以用，6.0报错
			String cacheDirPath=PathKit.getWebRootPath()+"/WEB-INF/uploadcache";
			//若文件夹不在则新建一个
			File file1 = new File(cacheDirPath);
			if(!file1.exists()){
				file1.mkdirs();
			}
		    factory.setRepository(file1);//设置缓存目录
			ServletFileUpload upload = new ServletFileUpload(factory);		
			upload.setProgressListener(new ProgressListener(){//监听当前进度
				public void update(long pBytesRead, long pContentLength, int pItems) {
					System.out.println("当前已解析：" + pBytesRead +"--pItems---"+pItems);
				}
			});
			upload.setFileSizeMax(1024*1024*400);//文件最大为100m
			upload.setHeaderEncoding("UTF-8");//解决中文乱码
			List<FileItem> list = upload.parseRequest(this.getRequest());
			for(FileItem item : list){
				if(item.isFormField()){
					//为普通输入项
					String inputName = item.getFieldName();
					String inputValue = item.getString("UTF-8");
					System.out.println(inputName + "="  + inputValue);
				}else{
					System.out.println(item.getFieldName()+"文件业务类型（论文或者附件)inputd的 name");
					fileType=item.getFieldName();
					String filename = item.getName().substring(item.getName().lastIndexOf("\\")+1);  //""	
					if(filename==null || filename.trim().equals("")){//文件名判空
						if("论文初稿附件".equals(fileType)||"论文定稿附件".equals(fileType))
						{
							System.out.println("文件空null-----进来了------");
							String table_name="";
							String table_mainkey="";
							String student_foreign_key="";
							String attachmenturl="";
							if("论文初稿附件".equals(fileType))
									{
								table_name="thesisinitdraft";
							    table_mainkey="initdraft_id";
								student_foreign_key="initdraft_student";
								attachmenturl="initdraft_attachmenturl";
									}
							if("论文定稿附件".equals(fileType))
							{
								table_name="ensuredraft";
							    table_mainkey="ensuredraft_id";
								student_foreign_key="ensuredraft_student";
								attachmenturl="ensuredraft_attachmenturl";
							}
						//对第一次上传初稿和定稿时没传附件进行处理，建附件路径设置为null-------------------------------------------
						sql="select student_id from student where student_no=?";
						Record student_id = Db.findFirst(sql,studentNo);//获取学生ID
						sql="select stu_rela_thesis_id from student_rela_thesistitle where stu_rela_thesis_stu=?";
						//获取学生论文表的虚拟主键
						Record stu_rela_thesis_id = Db.findFirst(sql,student_id.getInt("student_id").toString());
						//以下代码需要改动才可以共用----------------------------------------------------------------
						sql="select * from "+table_name+" where "+student_foreign_key+"=?";//论文初稿表
						Record thesisinitdraft = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id").toString());
						if(thesisinitdraft!=null)//初稿有记录的情况
						{
							if(thesisinitdraft.getStr(attachmenturl)==null)//初稿记录为空,则插入存储地址
								{
								thesisinitdraft.set(attachmenturl,"null");//第一次没有上传附件则把附件地址设为null
								if(Db.update(table_name,table_mainkey,thesisinitdraft))
									{
									bool=true;
									System.out.println(table_name+"第一次附件设置成功");
									}
								}
						}
						}
						//-------------------------------------------
						System.out.println("文件空null---------------------"+fileType);
						continue;
					}	
					String ext = filename.substring(filename.lastIndexOf(".")+1);//后缀名合法性判断
					List types = Arrays.asList("pdf","doc","DOC","PDF","ZIP","zip","rar","RAR");//合法类型
					if(!types.contains(ext)){
						System.out.println("文件类型不合法-----------------------------------------");
						return;
					}
					//-------------------------------------------------------down
					//可能需要改的部分代码
					
					
					//查找学生的专业id和年级
					sql="select student_department,student_grade from student where student_id=?";
					Record student = Db.findFirst(sql, studentNum);
					 departmentid=student.getInt("student_department")+"";//系id
					grade=student.getStr("student_grade");//年级
					sql="select department_no from department where department_id=?";
					Record studepartment = Db.findFirst(sql, departmentid);
					departmentNo=studepartment .getStr("department_no");//系编号
					//设置文件存储路径
					 saveDir="uploadDir"+File.separator+"student"+File.separator+departmentNo+File.separator+grade;
					 //
					if("开题报告正文".equals(fileType))
					{
						filename="开题报告正文."+ext;
						saveDir=saveDir+File.separator+"kickoff_report";
					}
					if("开题报告附件".equals(fileType))
					{
						filename="开题报告附件."+ext;
						saveDir=saveDir+File.separator+"kickoff_attachment";
					}
					if("论文初稿".equals(fileType))
					{
						filename="论文初稿."+ext;
						saveDir=saveDir+File.separator+"thesistemp_url";}
					if("论文初稿附件".equals(fileType))
					{
						filename="论文初稿附件."+ext;
						saveDir=saveDir+File.separator+"thesistemp_attachmenturl";
					}
					if("论文定稿".equals(fileType))
					{
						filename="论文定稿."+ext;
						saveDir=saveDir+File.separator+"ensuretemp_url";}
					if("论文定稿附件".equals(fileType))
					{
						filename="论文定稿附件."+ext;
						saveDir=saveDir+File.separator+"ensuretemp_attachmenturl";}
					if("论文最终稿".equals(fileType))
					{
						filename="论文最终稿."+ext;
						saveDir=saveDir+File.separator+"fthesis_url";}
					if("论文最终稿附件".equals(fileType))
					{
						filename="论文终稿附件."+ext;
						saveDir=saveDir+File.separator+"fthesis _attachmenturl";}
					
					//saveFileName = "学号_姓名_"+filename;//文件保存在服务器的名字
					saveFileName =studentNo+"_"+studentName+"_"+filename;//文件保存在服务器的名字
					
					//对初稿第一版进行
					//---------------------------------------------------------------up
					InputStream in = item.getInputStream();
					int len = 0;
					byte buffer[] = new byte[1024];
					String savepath =PathKit.getWebRootPath()+"/WEB-INF/"+saveDir;//文件保存路径
					//--------------------------------------------------------------------
					//若文件夹不在则新建一个
					File file = new File(savepath);
					if(!file.exists()){
						file.mkdirs();
					}
					System.out.println(savepath + File.separator + saveFileName+"--------------------");
					FileOutputStream out = new FileOutputStream(savepath + File.separator + saveFileName);
					while((len=in.read(buffer))>0){
						out.write(buffer, 0, len);
					}
					in.close();
					out.close();
					item.delete();  //删除临时文件
				}
				//接下来部分用于操作数据库,每个文件都要操作一次
				//数据库操作开始-----------------------------------------------------------------------
				sql="select student_id from student where student_no=?";
				Record student_id = Db.findFirst(sql,studentNo);//获取学生ID
				sql="select stu_rela_thesis_id from student_rela_thesistitle where stu_rela_thesis_stu=?";
				//获取学生论文表的虚拟主键
				Record stu_rela_thesis_id = Db.findFirst(sql,student_id.getInt("student_id").toString());
		
				//开题报告开始----------------------------------------------------------------------------
				
				if("开题报告正文".equals(fileType))
				{
					sql="select * from kickoffreport where kickoff_student=?";
					Record kickoffreport = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id".toString()));
					if(kickoffreport!=null){
						kickoffreport.set("kickoff_passtype","A").set("kickoff_newmemo","B").set("kickoff_newsubmit","A").set("kickoff_report",saveFileName).set("kickoff_submittime",new Date());
						if(Db.update("kickoffreport","kickoff_id",kickoffreport))//特殊字段：java日期格式.doc 会发生异常
							bool=true;
						else bool=false;
					}
					
					if(kickoffreport==null){
						kickoffreport=new Record().set("kickoff_student",stu_rela_thesis_id.getInt("stu_rela_thesis_id".toString())).set("kickoff_passtype","A").set("kickoff_newmemo","B").set("kickoff_newsubmit","A").set("kickoff_report",saveFileName).set("kickoff_submittime",new Date());
						if(Db.save("kickoffreport",kickoffreport))
							{
							bool=true;
							  System.out.println(kickoffreport.get("id")+"chaaaaa----------------"+kickoffreport.toString());
							}
						else bool=false;
					}
				}
				
				if("开题报告附件".equals(fileType))//
				{
					  sql="select * from kickoffreport where kickoff_student=?";//开题报告表
	                  Record kickoffreport = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id"));
	                  System.out.println("附件啦啦啦----------------"+stu_rela_thesis_id.getInt("stu_rela_thesis_id").toString());
	                  if(kickoffreport!=null)//开题报告附件有记录的情况
						{
							System.out.println("进来了----------------");
							kickoffreport.set("kickoff_attachment",saveFileName);
								if(Db.update("kickoffreport","kickoff_id",kickoffreport))
									{
									bool=true;
									System.out.println("kickoffreport更新成功");
									}
								else bool=false;
						}
					
				}
				//开题报告结束------------------------------------------------------------------------
				
				//论文初稿开始----------------------------------------------------------------------------------------------
				if("论文初稿".equals(fileType))
				{		
					sql="select * from thesisinitdraft where initdraft_student=?";//论文初稿表
					Record thesisinitdraft = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id").toString());
					if(thesisinitdraft!=null)//初稿有记录的情况
					{
						if(thesisinitdraft.getStr("initdraft_url")==null)//初稿记录为空,则插入存储地址
							{
							//
							moveFile(saveDir,saveFileName);
							//
							thesisinitdraft.set("initdraft_state","A").set("initdraft_newcomment","B").set("initdraft_newsubmit","A").set("initdraft_url","first_"+saveFileName).set("initdraft_stusubmittime",new Date());
							if(Db.update("thesisinitdraft","initdraft_id",thesisinitdraft))
								{
								bool=true;
								System.out.println("thesisinitdraft更新成功");
								}
							else bool=false;
							}
					}
					if(thesisinitdraft==null)//初稿记录为空的情况
					{
						System.out.println("----------------初稿记录为空的情况-------------------");
						//建文件移到第一稿存放位置--------------------------------------------
						moveFile(saveDir,saveFileName);
						//---------------------------------------------
						thesisinitdraft=new Record().set("initdraft_student",stu_rela_thesis_id.getInt("stu_rela_thesis_id")).set("initdraft_state","A").set("initdraft_newcomment","B").set("initdraft_newsubmit","A").set("initdraft_url","first_"+saveFileName).set("initdraft_stusubmittime",new Date());
					    if(Db.save("thesisinitdraft",thesisinitdraft))
					    	{
					    	bool=true;
					    	System.out.println("thesisinitdraft----id1"+thesisinitdraft.get("id"));
					    	System.out.println("thesisinitdraft插入成功");
					    	thesisinitdraft = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id").toString());
					    	if(thesisinitdraft==null)
					    		System.out.println("thesisinitdraft插入成功后查不到");
					    	}
					    else bool=false;
					}
					
					//--对初稿临时表的操作--------------------------------------------------
					sql="select * from thesismodifytemp where thesistemp_student=? and thesistemp_isstusubmit=?";//论文初稿修改临时表
					Record thesismodifytemp = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id").toString(),"A");
					if(thesismodifytemp!=null)//初稿修改临时有记录的情况
					{
						System.out.println("----------------初稿修改临时有记录的情况-------------------");
							thesismodifytemp.set("thesistemp_state","A").set("thesistemp_newcomment","B").set("thesistemp_url",saveFileName).set("thesistemp_submittime",new Date());
							if(Db.update("thesismodifytemp","thesistemp_id",thesismodifytemp))
								{
								bool=true;
								System.out.println("thesismodifytemp更新成功");
								}
							else bool=false;
					}
					if(thesismodifytemp==null)//初稿修改临时记录为空的情况
					{
						System.out.println("----------------初稿修改临时记录为空的情况-------------------");
						thesismodifytemp=new Record().set("thesistemp_student",stu_rela_thesis_id.getInt("stu_rela_thesis_id")).set("thesistemp_state","A").set("thesistemp_newcomment","B").set("thesistemp_isstusubmit","A").set("thesistemp_url",saveFileName).set("thesistemp_submittime",new Date());
					    if(Db.save("thesismodifytemp",thesismodifytemp))
					    	{
					    	bool=true;
					    	System.out.println("thesismodifytemp----id1"+thesisinitdraft.get("id"));
					    	System.out.println("thesismodifytemp插入成功");
					    	}
					    else bool=false;
					}
				}
				
				//论文初稿附件的数据库操作------------------------------------------------------------------------------------------------------
				if("论文初稿附件".equals(fileType))//在第一次提交论文时就应该把附件存入初稿表，若第一次没有存入，则以后都不存
				{
                  sql="select * from thesisinitdraft where initdraft_student=? ";//论文初稿表
                 
                  Record thesisinitdraft = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id").toString());
                  System.out.println("thesisDRAFT插入成功对附件进行处理--------"+thesisinitdraft.toString());
                  System.out.println("thesisDRAFT插入成功对附件进行处理--------"+thesisinitdraft.getInt("initdraft_student").toString());
					if(thesisinitdraft!=null)//初稿有记录的情况
					{
						 System.out.println("进来了--------------------------");
						if(thesisinitdraft.getStr("initdraft_attachmenturl")==null)
							{
							//建文件移到第一稿存放位置--------------------------------------------
							moveFile(saveDir,saveFileName);
							//---------------------------------------------
							thesisinitdraft.set("initdraft_attachmenturl","first_"+saveFileName);
							if(Db.update("thesisinitdraft","initdraft_id",thesisinitdraft))
								{
								bool=true;
								System.out.println("thesisinitdraft更新成功");
								}
							else bool=false;
							}
					}
					//论文初稿修改临时表附件---------------------------------------------------------------------------------------------------
				  sql="select * from thesismodifytemp where thesistemp_student=? and thesistemp_isstusubmit=?";//论文初稿修改临时表
				  Record thesismodifytemp = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id").toString(),"A");
					if(thesismodifytemp!=null)//初稿有记录的情况
					{
							thesismodifytemp.set("thesistemp_attachmenturl",saveFileName);
							if(Db.update("thesismodifytemp","thesistemp_id",thesismodifytemp))
								{
								bool=true;
								System.out.println("thesismodifytemp附件更新成功");
								}
							else bool=false;
					}
				}
				//论文初稿结束----------------------------------------------------------------------------------------------
				
				
				//论文定稿开始----------------------------------------------------------------------------------------------
				if("论文定稿".equals(fileType))
				{
					//----------------------------------------------------------------------------------------------
                    sql="select * from ensuredraft where ensuredraft_student=?";//论文定稿表
                	Record ensuredraft = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id").toString());
					if(ensuredraft!=null)//ensuredraft有记录的情况
					{
						if(ensuredraft.getStr("ensuredraft_url")==null)//ensuredraft记录为空,则插入存储地址
							{
							//建文件移到第一稿存放位置--------------------------------------------
							moveFile(saveDir,saveFileName);
							//---------------------------------------------
							ensuredraft.set("ensuredraft_newmemo","B").set("ensuredraft_newsubmit","A").set("ensuredraft_url","first_"+saveFileName).set("ensuredraft_submit",new Date());
							if(Db.update("ensuredraft","ensuredraft_id",ensuredraft))
								{
								bool=true;
								System.out.println("ensuredraft更新成功");
								}
							else bool=false;
							}
						
						//-------新增判断，会不停覆盖定稿表---后期可能要修改------------------------------------------------------------
						if(ensuredraft.getStr("ensuredraft_url")!=null)//ensuredraft记录为空,则插入存储地址
						{
						//建文件移到第一稿存放位置--------------------------------------------
						moveFile(saveDir,saveFileName);
						//---------------------------------------------
						ensuredraft.set("ensuredraft_newmemo","B").set("ensuredraft_newsubmit","A").set("ensuredraft_url","first_"+saveFileName).set("ensuredraft_submit",new Date());
						if(Db.update("ensuredraft","ensuredraft_id",ensuredraft))
							{
							bool=true;
							System.out.println("ensuredraft更新成功");
							}
						else bool=false;
						}
						//----------------------------------------------------------------------
					}
					if(ensuredraft==null)//ensuredraft记录为空的情况
					{
						System.out.println("----------------ensuredraft记录为空的情况-------------------");
						//建文件移到第一稿存放位置--------------------------------------------
						moveFile(saveDir,saveFileName);
						//---------------------------------------------
						ensuredraft=new Record().set("ensuredraft_student",stu_rela_thesis_id.getInt("stu_rela_thesis_id")).set("ensuredraft_tchconfirm1","A").set("ensuredraft_tchconfirm2","A").set("ensuredraft_newmemo","B").set("ensuredraft_newsubmit","A").set("ensuredraft_url","first_"+saveFileName).set("ensuredraft_submit",new Date());
					    if(Db.save("ensuredraft",ensuredraft))
					    	{
					    	bool=true;
					    	System.out.println("ensuredraft插入成功");
					    	}
					    else bool=false;
					}
					
                    //定稿临时表数据库操作开始----------------------------------------------------------------------------------------------
					sql="select * from ensuredrafttemp where ensuretemp_student=? and ensuretemp_isstusubmit=?";//论文定稿修改临时表
					Record ensuredraftTemp = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id").toString(),"A");
					
					if(ensuredraftTemp!=null)//ensuredraftTemp修改临时有记录的情况
					{
						System.out.println("----------------ensuredraftTemp修改临时有记录的情况-------------------");
						ensuredraftTemp.set("ensuretemp_url",saveFileName).set("ensuretemp_submittime",new Date());
							if(Db.update("ensuredrafttemp","ensuretemp_id",ensuredraftTemp))
								{
								bool=true;
								System.out.println("ensuredraftTemp更新成功");
								}
							else bool=false;
					}
					if(ensuredraftTemp==null)//ensuredraftTemp修改临时记录为空的情况
					{
						System.out.println("----------------ensuredraftTemp修改临时记录为空的情况-------------------");
						ensuredraftTemp=new Record().set("ensuretemp_student",stu_rela_thesis_id.getInt("stu_rela_thesis_id")).set("ensuretemp_url",saveFileName).set("ensuretemp_isstusubmit","A").set("ensuretemp_submittime",new Date());
					    if(Db.save("ensuredrafttemp",ensuredraftTemp))
					    	{
					    	bool=true;
					    	System.out.println("ensuredraftTemp插入成功");
					    	}
					    else bool=false;
					}
					
					
				}
			    if("论文定稿附件".equals(fileType))
				{
                    sql="select * from ensuredraft where ensuredraft_student=?";//论文定稿表
                    Record ensuredraft = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id").toString());
					if(ensuredraft!=null)//论文定稿附件有记录的情况
					{
						if(ensuredraft.getStr("ensuredraft_attachmenturl")==null)//最好能在数据库有字段标记第一次是否一存附件
						{
							ensuredraft.set("ensuredraft_attachmenturl",saveFileName);
							if(Db.update("ensuredraft","ensuredraft_id",ensuredraft))
								{
								bool=true;
								System.out.println("ensuredraft附件更新成功");
								}
							else bool=false;
						}
						
						//---------新增，会不停覆盖定稿表，后期可能要修改------------------------------------------------------
						if(ensuredraft.getStr("ensuredraft_attachmenturl")!=null)//最好能在数据库有字段标记第一次是否一存附件
						{
							ensuredraft.set("ensuredraft_attachmenturl",saveFileName);
							if(Db.update("ensuredraft","ensuredraft_id",ensuredraft))
								{
								bool=true;
								System.out.println("ensuredraft附件更新成功");
								}
							else bool=false;
						}
						//----------------------------------------------------------------
					}
					//论文定稿修改临时表附件---------------------------------------------------------------------------------------------------
					sql="select * from ensuredrafttemp where ensuretemp_student=? and ensuretemp_isstusubmit=?";//论文定稿修改临时表//论文定稿附件修改临时表
				  Record ensuredraftTemp = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id").toString(),"A");
					if(ensuredraftTemp!=null)//论文定稿附件有记录的情况
					{
						ensuredraftTemp.set("ensuretemp_attachmenturl",saveFileName);
							if(Db.update("ensuredrafttemp","ensuretemp_id",ensuredraftTemp))
								{
								bool=true;
								System.out.println("ensuredraftTemp附件更新成功");
								}
							else bool=false;
					}
					
				}
			  //论文定稿结束----------------------------------------------------------------------------------------------
			    
			  //论文最终稿开始----------------------------------------------------------------------------------------------
     			if("论文最终稿".equals(fileType))
     			{
                   sql="select * from finalthesis where fthesis_student=?";//论文最终稿表
                   Record finalthesis = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id".toString()));
					if(finalthesis!=null){
						finalthesis.set("fthesis_url",saveFileName).set("fthesis_newmemo","B").set("fthesis_confirm","A").set("fthesis_submittime",new Date());
						if(Db.update("finalthesis","fthesis_id",finalthesis))//特殊字段：java日期格式.doc 会发生异常
							bool=true;
						else bool=false;
					}
					
					if(finalthesis==null){
						finalthesis=new Record().set("fthesis_student",stu_rela_thesis_id.getInt("stu_rela_thesis_id".toString())).set("fthesis_newmemo","B").set("fthesis_confirm","A").set("fthesis_url",saveFileName).set("fthesis_submittime",new Date());
						if(Db.save("finalthesis",finalthesis))
							{
							bool=true;
							}
						else bool=false;
					}
				
     			}
				if("论文最终稿附件".equals(fileType))
				{
					   sql="select * from finalthesis where fthesis_student=?";//论文最终稿表
	                   Record finalthesis = Db.findFirst(sql,stu_rela_thesis_id.getInt("stu_rela_thesis_id".toString()));
	                  System.out.println("附件啦啦啦----------------"+stu_rela_thesis_id.getInt("stu_rela_thesis_id").toString());
	                  if(finalthesis!=null)//开题报告附件有记录的情况
						{
							System.out.println("进来了----------------");
							finalthesis.set("fthesis_attachmenturl",saveFileName);
								if(Db.update("finalthesis","fthesis_id",finalthesis))
									{
									bool=true;
									System.out.println("finalthesis更新成功");
									}
								else bool=false;
						}
				}
				
				//论文最终稿结束----------------------------------------------------------------------------------------------
				
				
				//数据库操作结束------------------------------------------------------------------------
				
			}
		}catch (FileUploadBase.FileSizeLimitExceededException e) {
			System.out.println("文件大小不能超过100m");
			renderJson("文件大小不能超过100m!");
		}catch (Exception e) {
			renderJson("上传失败!");
			System.out.println(e);
		}
		if(bool)
		{
		renderJson("上传成功！！");
		return;
		}
		renderJson("上传失败!");
}
	
	@ActionKey("/ReplyGroup")//答辩组组长和秘书信息
	public void ReplyGroup(){
        String departmentid="1";
		String sql="select * from teacher where teacher_department=?";//根据系编号得到教师
		List<Record> teacher_info = Db.find(sql,departmentid);
		renderJson(teacher_info);
	}
	
	@ActionKey("/ReplyGroupMajor")//答辩组专业
	public void ReplyGroupMajor(){
        String departmentid="1";
		String sql = "select * from major where major_department=?";
		List<Record> major_info = Db.find(sql,departmentid);
		renderJson(major_info);
	}
	//
	//秘书和组长需不需要与答辩组通过关联表关联?????????????
	//
	@ActionKey("/CreateReplyGroupSet")//答辩组组长和秘书信息
	public void CreateReplyGroup(){
        String departmentid="1";
        String groupname=getPara("groupname");
        String major_id=getPara("major");
        String zuzhan_no=getPara("zuzhan");
        String mishu_no=getPara("mishu");
        String address=getPara("groupaddress");     
        String time=getPara("time");
        Record teacher = null;
        String zuzhan_name = null;
        String mishu_name = null;
        String sql="select * from ReplyGroup1 where replygrp1_name=?";
        Record ReplyGroup = Db.findFirst(sql,groupname);
        if(ReplyGroup!=null)
        {
        	renderJson("false");
        	return;
        }
        sql="select teacher_name from teacher where teacher_no=?";
        if(!"".equals(zuzhan_no))
        {
        	teacher = Db.findFirst(sql,zuzhan_no);
        	zuzhan_name=teacher.getStr("teacher_name");
        }
       
        if(!"".equals(mishu_no))
         {
        	teacher = Db.findFirst(sql,mishu_no);
            mishu_name=teacher.getStr("teacher_name");
         }
       System.out.println(groupname+"  "+major_id+"  "+zuzhan_name+"  "+mishu_name);
       ReplyGroup = new Record()
       .set("replygrp1_name",groupname)
       .set("replygrp1_major",major_id)
       .set("replygrp1_headno",zuzhan_no)
       .set("replygrp1_headname",zuzhan_name)
       .set("replygrp1_secretaryno",mishu_no)
       .set("replygrp1_secretaryname",mishu_name)
       .set("replygrp1_time",time)
       .set("replygrp1_place",address);
       if(Db.save("ReplyGroup1",ReplyGroup))
    	   renderJson("true");
       else
    	   renderJson("false");
	}
	

	@ActionKey("/DelReplyGroup")
	public void DelReplyGroup(){//删除答辩组
	      String groupId[]=getParaValues("array[]");
	      String msg,code;
	      Map<String, String> map=new HashMap<String, String>();
	      int i = 0;
	      String sql="delete from replygroup1_rela_student where replygrp1_rela_stu_replygrp1=?";
	      try{
	    	  System.out.println(groupId.length);
	    	  for(i=0;i<groupId.length;i++)
	    	    	Db.update(sql,groupId[i]);
	    	  sql="delete from replygroup1_rela_teacher where Replygrp1_rela_tch_replygrp1=?";
	    	  for(i=0;i<groupId.length;i++)
	    	    	Db.update(sql,groupId[i]);
	    	  sql="delete from replygroup1 where replygrp1_id=?";
	    	  for(i=0;i<groupId.length;i++)
	    	    	Db.update(sql,groupId[i]);
	    	  msg="已成功删除："+i+"条记录";
	    	  code="1";
	    	  map.put("msg",msg);
	    	  map.put("code",code);
	    	  renderJson(map);
	      }catch(Exception e){
	    	  msg="已成功删除："+i+"条"+"仍有"+(groupId.length-i)+"条删除失败";
	    	  code="1";
	    	  map.put("msg",msg);
	    	  map.put("code",code);
	    	  renderJson(map);
	      }
	      
	}
	
	
	@ActionKey("/GetReplyGroupInfo")//答辩组信息
	public void GetReplyGroupInfo(){
        String departmentid="1";
		String sql = "select * from major where major_department=?";
		List<Record> major_info = Db.find(sql,departmentid);
		List<Record> ReplyGroup1=null;
		List<Record> ReplyGroupTemp=null;
		sql="select * from dabianzu1_replygroup_rel_major where replygrp1_major=?";
		for(int i=0;i<major_info.size();i++){
			ReplyGroup1=Db.find(sql,major_info.get(i).getInt("major_id"));
			System.out.println(major_info.get(i).getInt("major_id"));
			if(ReplyGroupTemp==null)
				ReplyGroupTemp=ReplyGroup1;
			else
			ReplyGroupTemp.addAll(ReplyGroup1);
			
		}
		if(ReplyGroupTemp==null)
			return;
		renderJson(ReplyGroupTemp);
	}
	
	@ActionKey("/GroupManTableInfo")//答辩组教师信息
	public void GroupManTableInfo(){
        String ReplyGroupid=getPara("groupid");
        
        List<Record> teacher_info=null;
		String sql = "select * from dabianzu1_ReplyGroup1_Rela_Teacher where replygrp1_id=?";
	    teacher_info = Db.find(sql,ReplyGroupid);
		if(teacher_info==null)
			return;
		System.out.println("pppppppppppppppppppppppppppp");
		renderJson(teacher_info);
	}
	
	@ActionKey("/DelGroupMan")//删除答辩组教师成员，根据成员ID
	public void DelGroupMan(){
	  String ReplyGroupid=getPara("groupid");
      String teacherid[]=getParaValues("array[]");
      String msg,code;
      Map<String, String> map=new HashMap<String, String>();
      int i = 0;
      //List<String> resultList=new ArrayList<String>();
      String sql="delete from replygroup1_rela_teacher where replygrp1_rela_tch_tch=? and replygrp1_rela_tch_replygrp1=?";
      try{
    	  for(i=0;i<teacherid.length;i++)
    	    	Db.update(sql,teacherid[i],ReplyGroupid);
    	  msg="已成功删除："+i+"条记录";
    	  code="1";
    	  map.put("msg",msg);
    	  map.put("code",code);
    	  renderJson(map);
      }catch(Exception e){
    	  msg="已成功删除："+i+"条"+"仍有"+(teacherid.length-i)+"条删除失败";
    	  code="1";
    	  map.put("msg",msg);
    	  map.put("code",code);
    	  renderJson(map);
      }
      
	}
	
	@ActionKey("/AddTeacherToGroup")//答辩组添加教师
	public void AddTeacherToGroup(){
        String ReplyGroupid=getPara("groupid");
        String teacherid[]=getParaValues("array[]");
        String msg,code;
        Map<String, String> map=new HashMap<String, String>();
        int i = 0;
        Record group1_rel_tcher = null;
        try{
      	  for(i=0;i<teacherid.length;i++)
      		{
      		  group1_rel_tcher= new Record()
      	                        .set("replygrp1_rela_tch_replygrp1",ReplyGroupid)
      	                        .set("replygrp1_rela_tch_tch",teacherid[i]);
      	      Db.save("replygroup1_rela_teacher","replygrp1_rela_tch_id",group1_rel_tcher);
      		}
      	  msg="已成功保存："+i+"条记录";
      	  code="1";
      	  map.put("msg",msg);
      	  map.put("code",code);
      	  renderJson(map);
        }catch(Exception e){
      	  msg="已成功保存："+i+"条"+"仍有"+(teacherid.length-i)+"条保存失败";
      	  code="1";
      	  map.put("msg",msg);
      	  map.put("code",code);
      	  renderJson(map);
        }
	}
	
	@ActionKey("/StudentWhoReply")//获取申请答辩的学生
	public void StudentWhoReply(){
		String department_id="1";
		String sql="select student_id,student_no,student_name,student_major,student_fulltel from student where student_replyconfirm=? and student_department=? and student_id not in(select replygrp1_rela_stu_stu from replygroup1_rela_student)";
		List<Record> replyStudent = Db.find(sql,"B",department_id);//B代表申请答辩
		renderJson(replyStudent);
	}
	
	
	@ActionKey("/ReplyStudent")//获取答辩的学生
	public void ReplyStudent(){
		String sql="select student_id,student_no,student_name,student_major,student_fulltel from student where student_replyconfirm=? and student_id  in(select replygrp1_rela_stu_stu from replygroup1_rela_student where replygrp1_rela_stu_replygrp1=?)";
		 String ReplyGroupid=getPara("groupid");
		List<Record> replyGroupStudent = Db.find(sql,"B",ReplyGroupid);
		renderJson(replyGroupStudent);
	}
	
	@ActionKey("/DelGroupStudent")//删除答辩组学生成员，根据成员ID
	public void DelGroupStudent(){
	  String ReplyGroupid=getPara("groupid");
      String studentId[]=getParaValues("array[]");
      String msg,code;
      Map<String, String> map=new HashMap<String, String>();
      int i = 0;
      //List<String> resultList=new ArrayList<String>();
      String sql="delete from replygroup1_rela_student where replygrp1_rela_stu_stu=? and replygrp1_rela_stu_replygrp1=?";
      try{
    	  System.out.println(studentId.length);
    	  for(i=0;i<studentId.length;i++)
    	    	Db.update(sql,studentId[i],ReplyGroupid);
    	  msg="已成功删除："+i+"条记录";
    	  code="1";
    	  map.put("msg",msg);
    	  map.put("code",code);
    	  renderJson(map);
      }catch(Exception e){
    	  msg="已成功删除："+i+"条"+"仍有"+(studentId.length-i)+"条删除失败";
    	  code="1";
    	  map.put("msg",msg);
    	  map.put("code",code);
    	  renderJson(map);
      }
      
	}
	
	@ActionKey("/AddStudentToGroup")//答辩组添加学生
	public void AddStudentToGroup(){
        String ReplyGroupid=getPara("groupid");
        String studentId[]=getParaValues("array[]");
        String msg,code;
        Map<String, String> map=new HashMap<String, String>();
        int i = 0;
        Record group1_rel_student = null;
        try{
      	  for(i=0;i<studentId.length;i++)
      		{
      		  group1_rel_student= new Record()
      	                        .set("replygrp1_rela_stu_replygrp1",ReplyGroupid)
      	                        .set("replygrp1_rela_stu_stu",studentId[i]);
      	      Db.save("replyGroup1_rela_student","replygrp1_rela_stu_id",group1_rel_student);
      		}
      	  msg="已成功保存："+i+"条记录";
      	  code="1";
      	  map.put("msg",msg);
      	  map.put("code",code);
      	  renderJson(map);
        }catch(Exception e){
      	  msg="已成功保存："+i+"条"+"仍有"+(studentId.length-i)+"条保存失败";
      	  code="1";
      	  map.put("msg",msg);
      	  map.put("code",code);
      	  renderJson(map);
        }
	}
	
	
	
	
	/**
	 * 论文重要时间页面
	 */
	@ActionKey("keytime")
	public void keyTime_page()
	{
		String stunumber = "04120802";
		int stuId=getSessionAttr("stuNum");
		render("/pages1/stu_3.jsp");
	}
	
	/**
	 * 重要时间表格
	 */
	public void keyTime_table()
	{
		String stunumber = "04120802";
		int stuId=getSessionAttr("stuNum");
		Integer pageNumber = getParaToInt("page");
		Integer pageSize = getParaToInt("rows");
		Page<PaperKeyTime> keytime=PaperKeyTime.dao.selectTime(pageNumber, pageSize, stuId);
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("total", keytime.getTotalRow());
		m.put("rows", keytime.getList());
		renderJson(m);
	}
	
	/**
	 * 学生申报课题页面
	 */
	@ActionKey("/applyDis")
	public void stuAddDis_page()
	{
		int stuId=getSessionAttr("stuNum");
		setAttr("stu_tch", DbFun.dao.stu_tch(stuId));
		setAttr("thesissourceList", Thesissource.dao.selectSource(stuId));
		setAttr("state", Thesistitle.dao.checkState(stuId));
		render("/pages1/stu_1.jsp");
	}
	
	/**
	 * 学生申报课题操作
	 */
	public void stuAddDis(){
		boolean sign = false;
		String stu_number = "04120802";
		int stuId=getSessionAttr("stuNum");
		String thesistitle_name = null;
		String thesistitle_source = null;
		String thesistitle_projectname = null;
		String thesistitle_projectno = null;
		Date time=new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
		String date = dateFormat.format(time); 
		Map m=new HashMap();
		String msg = null;
//		String stunumber = getSessionAttr("studentId");
		try {
			thesistitle_name = new String(getPara("thesistitle.thesistitle_name").getBytes("iso8859-1"),"utf-8");
			thesistitle_source=new String(getPara("thesistitle.thesistitle_source").getBytes("iso8859-1"),"utf-8");
			thesistitle_projectname=new String(getPara("thesistitle.Thesistitle_projectname").getBytes("iso8859-1"),"utf-8");
			thesistitle_projectno=new String(getPara("thesistitle.thesistitle_projectno").getBytes("iso8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String  sql="select stu_rela_thesis_id from student_rela_thesistitle where stu_rela_thesis_stu="+stuId+"";
		Integer srtId=Db.queryInt(sql);
		if(srtId!=null)
		{
			msg="你已提交或选择论文，不能重新申报！";
		}
		else{
			sql="SELECT thesistitle_name from thesistitle WHERE thesistitle_name='"+thesistitle_name+"'";
			String name=Db.queryStr(sql);
			if(name==null)
			{
				Record thesistitle=new Record().set("thesistitle_name",thesistitle_name).set("thesistitle_type", "设计")
						.set("thesistitle_source", thesistitle_source).set("thesistitle_projectno", thesistitle_projectno)
						.set("Thesistitle_projectname", thesistitle_projectname).set("thesistitle_select_way", "A")
						.set("thesistitle_checkstate", "A").set("thesistitle_selected","A").set("thesistitle_submittime",date);
				sign=Db.save("thesistitle", thesistitle);
				sql="select thesistitle_id from thesistitle where thesistitle_name='"+thesistitle_name+"' and thesistitle_submittime='"+date+"'";
				int id=Db.queryInt(sql);
				System.out.println(id);
				if(sign)
				{
	/*				sql="select stu_rela_thesis_id from student_rela_thesistitle where stu_rela_thesis_stu="+stuId+"";
					Integer srtId=Db.queryInt(sql);
					if(srtId!=null)
					{
						Db.deleteById("student_rela_thesistitle", "stu_rela_thesis_id", srtId);
					}
	*/
					Record student_rela_thesistitle=new Record().set("stu_rela_thesis_stu", stuId).set("stu_rela_thesis_thesis",id);
					sign=Db.save("student_rela_thesistitle", student_rela_thesistitle);
					System.out.println("Save");
				}
			}
			else {
				msg="该论文题目已存在，请重新修改提交";
				System.out.println("Error");
			}
			System.out.println(sign);
			if(sign)
				msg="论文题目提交成功";
		}
		m.put("sign", sign);
		m.put("msg", msg);
		renderJson(m);
	}
	
	/**
	 * 学生论文查重页面
	 */
	@ActionKey("/ensurer_page")
	public void ensurer_page()
	{
		String stunumber = "04120802";
		int stuId=getSessionAttr("stuNum");
		setAttr("stu_tch", DbFun.dao.stu_tch(stuId));
		render("/pages1/stu_8.jsp");
	}
	
	/**
	 * 论文查重结果表格
	 */
	public void ensurer_table()
	{
		int stuId=getSessionAttr("stuNum");
		String type="A";
		Integer pageNumber = getParaToInt("page");
		Integer pageSize = getParaToInt("rows");
		Page<Record> ens=DbFun.dao.select_ensurer(pageNumber, pageSize, stuId);
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("total", ens.getTotalRow());
		m.put("rows", ens.getList());
		renderJson(m); 
	}
	
	/**
	 * 论文查重页面查看教师意见操作
	 */
	public void ensurer_memo()
	{
		int stuId=getSessionAttr("stuNum");
		String type="A";
		String memo=DbFun.dao.teacher_memo(stuId, type);
		System.out.println(memo);
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("msg", memo);
		renderJson(m); 
	}
	
	/**
	 * 下载查重结果
	 */
	public void ensurer_result() throws UnsupportedEncodingException
	{
		int stuId=getSessionAttr("stuNum");
		String url=DbFun.dao.ensurerUrl(stuId);
		String Url=getClass().getResource("/").getFile().toString();
		Url=Url.substring(0,Url.lastIndexOf("/WEB-INF"));
		Url=URLDecoder.decode(Url,"utf-8");
		File file=new File(Url+"/WEB-INF/uploadDir/student/04/2011/ensuretemp_url_first"+url);
		System.out.println(Url+"/WEB-INF/uploadDir/student/04/2011/ensuretemp_url_first"+url);
		System.out.println("isFile:"+file.isFile());
		System.out.println("文件下载");
		renderFile(file);
		System.out.println("下载完成");
	}

	
	/**
	 * 申请答辩页面
	 */
	@ActionKey("/apply_page")
	public void apply_page()
	{
		int stuId=getSessionAttr("stuNum");
		setAttr("stu_tch", DbFun.dao.stu_tch(stuId));
		render("/pages1/stu_10.jsp");
	}
	
	/**
	 * 申请答辩页面表格
	 */
	public void apply_table()
	{
		int stuId=getSessionAttr("stuNum");
		Integer pageNumber = getParaToInt("page");
		Integer pageSize = getParaToInt("rows");
		Page<Record> app=DbFun.dao.select_stu_tch_thes(pageNumber, pageSize, stuId);
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("total", app.getTotalRow());
		m.put("rows", app.getList());
		renderJson(m);
	}
	
	/**
	 * 申请答辩
	 */
	public void apply()
	{
		boolean success=false;
		int stuId = getSessionAttr("stuNum");
		System.out.println(stuId+"申请答辩");
		success=DbFun.dao.apply(stuId);
		renderJson("{\"success\":"+success+"}");
	}
	
	/**
	 * 查看答辩组页面
	 */
	@ActionKey("/checkApply_page")
	public void checkApply_page()
	{
		int stuId=getSessionAttr("stuNum");
		render("/pages1/stu_11.jsp");
	}
	
	/**
	 * 查看答辩组页面表格
	 */
	public void checkApply_table()
	{
		int stuId=getSessionAttr("stuNum");
		Integer pageNumber = getParaToInt("page");
		Integer pageSize = getParaToInt("rows");
		Page<Record> app=DbFun.dao.select_stu_tch_thes(pageNumber, pageSize, stuId);
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("total", app.getTotalRow());
		m.put("rows", app.getList());
		renderJson(m);
	}
	
	/**
	 * 查看答辩组
	 */
	public void checkGroupMsg()
	{
		int stuId=getSessionAttr("stuNum");
		renderJson(DbFun.dao.replygroup(stuId));
	}


	


}
